package com.ls.lserp.modules.sys.web;

import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ls.lserp.modules.sys.utils.SystemMessageUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.BaseEntity;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.Constants;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.sys.entity.Dict;
import com.ls.lserp.modules.sys.entity.Menu;
import com.ls.lserp.modules.sys.entity.Shop;
import com.ls.lserp.modules.sys.entity.User;
import com.ls.lserp.modules.sys.service.SystemService;
import com.ls.lserp.modules.sys.utils.DictUtils;
import com.ls.lserp.modules.sys.utils.UserUtils;

/**
 * 用户Controller
 * @author LiuPeng
 * @version 2016-10-14
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/user")
public class UserController extends BaseController {

    @Autowired
    private SystemService systemService;

    @Autowired
    private LocaleResolver localeResolver;

    @ModelAttribute
    public User get(@RequestParam(required = false) String id) {
        if (StringUtils.isNotBlank(id)) {
            return systemService.getUser(Long.parseLong(id));
        } else {
            return new User();
        }
    }

    /**
     * 用户列表
     * 
     * @param user
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequiresPermissions("sys:user:view")
    @RequestMapping(value = { "list", "" })
    public String list(User user, HttpServletRequest request,HttpServletResponse response, Model model) {
    	Long shopId=UserUtils.getUser().getShop().getId();
    	
    	Shop shop=new Shop();
    	shop.setId(shopId);
    	
    	user.setShop(shop);
    	
    	Page<User> page = systemService.findUser(new Page<User>(request,response), user);
      
        
        model.addAttribute("page", page);
        model.addAttribute("shopId", shopId);
        return "modules/sys/userList";
    }

    /**
     * 联动返回城市
     * 
     * @param code
     * @param response
     * @return
     */
    @RequiresPermissions("sys:user:view")
    @RequestMapping(value = "city")
    @ResponseBody
    public String city(String code,  HttpServletResponse response) {

        List<Dict> cityList = DictUtils.getDictList(code);

        return renderString(response, cityList);

    }

    /**
     * 进入编辑用户页面
     * 
     * @param user
     * @param model
     * @return
     */
    @RequiresPermissions("sys:user:edit")
    @RequestMapping(value = "form")
    public String form(User user, RedirectAttributes redirectAttributes,Model model) {
        
        model.addAttribute("user", user);
        model.addAttribute("allRoles", systemService.findAllRole());
        return "modules/sys/userEdit";
    }

    /**
     * 进入查看用户页面
     * 
     * @param user
     * @param model
     * @return
     */
    @RequiresPermissions("sys:user:view")
    @RequestMapping(value = "show")
    public String show(User user, Model model) {
    	
    	Long shopId=UserUtils.getUser().getShop().getId();
    	
    	Shop shop=new Shop();
    	shop.setId(shopId);
    	user.setShop(shop);
    	
    	model.addAttribute("shopId", shopId);
        model.addAttribute("user", user);
        model.addAttribute("allRoles", systemService.findAllRole());
        return "modules/sys/userShow";
    }

    /**
     * 选择语言
     * 
     * @param language
     * @param request
     * @param response
     * @return
     */
    @RequiresPermissions("user")
    @RequestMapping(value = "language")
    @ResponseBody
    public String language(String language, HttpServletRequest request,HttpServletResponse response) {

        language = language.toLowerCase();

        if (language.equals(Constants.EN_US)) {
            localeResolver.setLocale(request, response, Locale.US);
        }else if(language.equals(Constants.JA_JP)){
        	localeResolver.setLocale(request, response, Locale.JAPAN);
        }
        else {
            localeResolver.setLocale(request, response, Locale.CHINA);
        }
        request.getSession().setAttribute(Constants.LANGUAGE,localeResolver.resolveLocale(request).toString().toLowerCase());
        return "true";
    }

    /**
     * 首页菜单
     * 
     * @param menuId
     * @param request
     * @param response
     * @return
     */
    @RequiresPermissions("user")
    @RequestMapping(value = "homemenu")
    @ResponseBody
    public String homemenu(String menuId, HttpServletRequest request,HttpServletResponse response) {

        // 定义返回字符窜
        String remenu = StringUtils.EMPTY;

        Map<String, Menu> map = new HashMap<String, Menu>();

        // 取得菜单列表
        List<Menu> menuList = UserUtils.getMenuList();

        // 放入Map
        for (Menu menu : menuList) {

            map.put(menu.getId().toString(), menu);

        }
        // 取得当前菜单
        Menu m = map.get(menuId.toString());

        // 取得父菜单
        String parent = m.getParentIds();

        String parentArray[] = parent.substring(0, parent.length() - 1).split(
                ",");
        // 循环父菜单
        for (String s : parentArray) {
            if (!"0".equals(s))
                remenu += "<span>" + map.get(s).getMenuName() + "</span>" + ">";
        }
        remenu += "<span class='active'>" + m.getMenuName() + "</span>";

        return renderString(response, remenu);
    }

    /**
     * 保存用户信息
     * 
     * @param user
     * @param request
     * @param model
     * @param response
     * @return
     */
    @RequiresPermissions("sys:user:edit")
    @RequestMapping(value = "save")
    @ResponseBody
    public String save(User user, HttpServletRequest request, Model model,HttpServletResponse response) {
        // 如果新密码为空，则不更换密码
        if (StringUtils.isNotBlank(user.getNewPassword())) {
            
            user.setPassword(SystemService.entryptPassword(user.getNewPassword()));
        }
        if(user.getId() != null&&systemService.checkEmailName(user)!=null){
        	if(!user.getId().toString().equals(systemService.checkEmailName(user).getId().toString())){
        		return renderString(response,AjaxDone.error(getText("user_emailExist")));
        	}
        }else{
        	if(systemService.checkEmailName(user)!=null){
        		return renderString(response,AjaxDone.error(getText("user_emailExist")));
        	}
        }
        
        if (user.getId() != null) {
            //判断数据是否删除
            User userNew=get(user.getId().toString());
            if(userNew==null || BaseEntity.DEL_FLAG_DELETE.equals(userNew.getDeleteFlag())){
                return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
            }
            //排他
            if (user.getVersion() == get(user.getId().toString()).getVersion()) {
                user.setVersion(user.getVersion() + 1);
            } else {
                return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
            }
        }

        try {
            // 保存用户信息
            systemService.saveUser(user);

            // 清除当前用户缓存
            if (user.getLoginName().equals(UserUtils.getUser().getLoginName())) {
                UserUtils.clearCache();
            }
            return renderString(response, AjaxDone.ok(SystemMessageUtils.getMessageName ( "userSaveSuccess")));

        } catch (Exception e) {
            // 记录日志
            logger.error(e.getMessage(), e);
            return renderString(response, AjaxDone.error(getText("System_error_please_contact_your_administrator")));
        }
    }

    @RequiresPermissions("sys:user:edit")
    @RequestMapping(value = "delete")
    public String delete(User user, HttpServletResponse response) {

        if (UserUtils.getUser().getId().equals(user.getId())) {
            // 不能删除登录用户
            return renderString(response, AjaxDone.error(getText("user_errorMessage")));
        } else if (User.isAdmin(user.getId())) {
            return renderString(response,AjaxDone.error(getText("user_errorMessage2")));
        } else {
            try {
                systemService.deleteUser(user);
            } catch (Exception e) {
                // 记录日志
                logger.error(e.getMessage(), e);
                return renderString(response, AjaxDone.error(getText("System_error_please_contact_your_administrator")));
            }
            return renderString(response, AjaxDone.ok(getText("user_deletSuccess")));
        }
    }

    /**
     * 验证登录名是否有效
     * 
     * @param oldLoginName
     * @param loginName
     * @return
     */
    @ResponseBody
    @RequiresPermissions("sys:user:edit")
    @RequestMapping(value = "checkLoginName")
    public String checkLoginName(String oldLoginName, String loginName) {
        if (loginName != null && loginName.equals(oldLoginName)) {
            return "true";
        } else if (loginName != null&& systemService.getUserByLoginName(loginName) == null) {
            return "true";
        }
        return "false";
    }

    /**
     * 返回用户信息
     * 
     * @return
     */
    @RequiresPermissions("user")
    @ResponseBody
    @RequestMapping(value = "infoData")
    public User infoData() {
        return UserUtils.getUser();
    }

    /**
     * 修改个人用户密码(该功能暂未开发)
     * 
     * @param oldPassword
     * @param newPassword
     * @param model
     * @return
     */
    @RequiresPermissions("user")
    @RequestMapping(value = "modifyPwd")
    public String modifyPwd(String oldPassword, String newPassword, Model model) {
        User user = UserUtils.getUser();
        if (StringUtils.isNotBlank(oldPassword)&& StringUtils.isNotBlank(newPassword)) {
            if (SystemService.validatePassword(oldPassword, user.getPassword())) {
                systemService.updatePasswordById(user.getId(),user.getLoginName(), newPassword);
                model.addAttribute("message", "修改密码成功");
            } else {
                model.addAttribute("message", "修改密码失败，旧密码错误");
            }
        }
        model.addAttribute("user", user);
        return "modules/sys/userModifyPwd";
    }

}
